package com.cms.recursoshumanos.component.base;

import com.cms.recursoshumanos.component.interfaces.URLDataCallback;
import com.cms.recursoshumanos.utilities.HttpIimageDataExtrator;

import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;

public class URLBitmapField extends BitmapField implements URLDataCallback 
{
	EncodedImage result;
	public static EncodedImage _encoded_img;
	
	int _imgWidth = 62;
	int _imgHeight = 62;
	int _imgMargin = 10;
	public URLBitmapField()
	{
		
	}
	
	public URLBitmapField(String url) 
	{
	    try 
	    {
	        HttpIimageDataExtrator.getWebData(url, this);
	    }
	    catch (Exception e) 
	    {
	    	e.printStackTrace();
	    }
	}
	
	public Bitmap getBitmap() 
	{
	    if (_encoded_img == null) 
		{
	    	return null;
		}
	    return _encoded_img.getBitmap();
	}
	
	public void callback(final String data) 
	{
	    if (data.startsWith("Exception"))
	    {
	    	return;
	    }
	
	    try 
	    {
	        byte[] dataArray = data.getBytes();
	
	        //bitmap = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length);//no scale
	
	        _encoded_img = EncodedImage.createEncodedImage(dataArray, 0, dataArray.length); // with scale
	        _encoded_img = sizeImage(_encoded_img, _imgWidth, _imgHeight);
	
	        this.setImage(_encoded_img);
	        UiApplication.getUiApplication().getActiveScreen().invalidate();
	    }
	    catch (final Exception e)
	    {
	    	e.printStackTrace();
	    }
	}
	
	public EncodedImage sizeImage(EncodedImage image, int width, int height) 
	{
	
	
	      int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
	      int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
	
	      int requiredWidthFixed32 = Fixed32.toFP(width);
	      int requiredHeightFixed32 = Fixed32.toFP(height);
	
	      int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
	        requiredWidthFixed32);
	      int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
	        requiredHeightFixed32);
	
	      result = image.scaleImage32(scaleXFixed32, scaleYFixed32);
	      return result;
	}



}




